package com.xiaoshuidi.cloud.module.rooms.controller.admin.iot;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaoshuidi.cloud.framework.common.exception.enums.GlobalErrorCodeConstants;
import com.xiaoshuidi.cloud.framework.common.pojo.CommonResult;
import com.xiaoshuidi.cloud.framework.common.pojo.PageResult;
import com.xiaoshuidi.cloud.framework.oss.core.OosFileService;
import com.xiaoshuidi.cloud.module.iot.api.device.DeviceApi;
import com.xiaoshuidi.cloud.module.iot.api.device.vo.DeviceDosageVo;
import com.xiaoshuidi.cloud.module.rooms.controller.admin.iot.vo.*;
import com.xiaoshuidi.cloud.module.rooms.controller.admin.pricing.vo.DeviceAmmterExportVo;
import com.xiaoshuidi.cloud.module.rooms.controller.admin.pricing.vo.DeviceDoorlockExportVo;
import com.xiaoshuidi.cloud.module.rooms.controller.admin.pricing.vo.DeviceWorterExportVo;
import com.xiaoshuidi.cloud.module.rooms.controller.admin.pricing.vo.HousePricingExportResp;
import com.xiaoshuidi.cloud.module.rooms.enums.ApiConstants;
import com.xiaoshuidi.cloud.module.rooms.enums.DevicePriceType;
import com.xiaoshuidi.cloud.module.rooms.pojo.*;
import com.xiaoshuidi.cloud.module.rooms.repository.*;
import com.xiaoshuidi.cloud.module.rooms.service.*;
import com.xiaoshuidi.cloud.module.rooms.vo.DevicePayTypeVo;
import com.xiaoshuidi.cloud.module.rooms.vo.RoomDevicePeakValleyPriceVo;
import com.xiaoshuidi.cloud.module.rooms.vo.RoomDeviceStairVo;
import com.xiaoshuidi.cloud.module.rooms.vo.RoomSdiotWaringVo;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jodd.util.StringUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @BelongsProject: lease-module-rooms
 * @BelongsPackage: com.xiaoshuidi.cloud.module.rooms.controller.admin.iot
 * @Author: James
 * @CreateTime: 2023-05-26  09:01
 * @Description: TODO
 * @Version: 1.0
 */
@Slf4j
@Tag(name = "设备管理 - 智能门锁")
@RestController
@RequestMapping(ApiConstants.NAME + "/device")
@RequiredArgsConstructor
public class IotDeviceController {
    @Autowired
    private IotDeviceService iotDeviceService;
    @Autowired
    private OosFileService oosFileService;
    @Autowired
    private IotWaringRepository iotWaringRepository;
    @Autowired
    private IotRoomAassociationRepository iotRoomAassociationRepository;
    @Autowired
    private IotWaringInfoRepository iotWaringInfoRepository;
    @Autowired
    private IRoomSdiotWaringService iRoomSdiotWaringService;
    @Autowired
    private IotRoomDevicePriceAssociationRepository iotRoomDevicePriceAssociationRepository;
    @Autowired
    private IotRoomDevicePriceRepository iotRoomDevicePriceRepository;
    @Autowired
    private IotRoomDeviceStairPriceRepository iotRoomDeviceStairPriceRepository;
    @Autowired
    private IotRoomDevicePeakValleyPriceRepository iotRoomDevicePeakValleyPriceRepository;
    @Autowired
    private IRoomDevicePriceAssociationService iRoomDevicePriceAssociationService;
    @Autowired
    private IRoomDeviceStairPriceService iRoomDeviceStairPriceService;
    @Autowired
    private IRoomDevicePeakValleyPriceService iRoomDevicePeakValleyPriceService;
    @Autowired
    private RoomSdiotDeviceMappingService roomSdiotDeviceMappingService;
    @Autowired
    private DeviceApi deviceApi;
    @Autowired
    private IotDeviceRepository iotDeviceRepository;

    /*
     * @description:获取已绑定设备列表
     * @author: James
     * @date: 2023/5/27 14:02
     * @param: [deviceReaVo]
     * @return: java.util.List<com.xiaoshuidi.cloud.module.rooms.controller.admin.iot.vo.DeviceReaVo>
     **/
    //@PreAuthorize("@ss.hasAnyPermissions('rooms:device:query')")
    @GetMapping("/device-ist")
    public CommonResult<PageResult<DeviceReaVo>> getDeviceList(DeviceReaVo deviceReaVo) {
        return iotDeviceService.getDeviceList(deviceReaVo);
    }

    /*
     * @description:根据设备类型导出绑定设备列表 todo @James 常量要定义枚举或者常量类
     * @author: James
     * @date: 2023/5/29 11:53
     * @param: [deviceReaVo]
     * @return: com.xiaoshuidi.cloud.module.rooms.controller.admin.pricing.vo.HousePricingExportResp
     **/
    //@PreAuthorize("@ss.hasAnyPermissions('rooms:device:export')")
    @GetMapping("/device-export")
    public CommonResult<HousePricingExportResp> deviceExport(DeviceReaVo deviceReaVo) {
        CommonResult<List<DeviceReaVo>> result = iotDeviceService.getDeviceListNoPages(deviceReaVo);
        String fileName = "设备列表.xlsx";
        if (result.getData().size() > 0) {
            List<DeviceReaVo> list = result.getData();
            if (StringUtil.isNotBlank(deviceReaVo.getDeviceType())) {
                if (deviceReaVo.getDeviceType().equals("doorlock")) {
                    List<DeviceDoorlockExportVo> doorlockExportVos = new ArrayList<>();
                    for (DeviceReaVo dr : list) {
                        DeviceDoorlockExportVo doorlockExportVo = new DeviceDoorlockExportVo();
                        doorlockExportVo.setDeviceNo(dr.getDeviceThirdNo());
                        doorlockExportVo.setRoomName(dr.getRoomName());
                        doorlockExportVo.setBatteryLevel(dr.getBatteryLevel());
                        doorlockExportVo.setUpdateTime(dr.getUpdateTime());
                        if (String.valueOf(dr.getOnlineStatus()).equals("1")) {
                            doorlockExportVo.setOnlineStatus("在线");
                        } else {
                            doorlockExportVo.setOnlineStatus("离线");
                        }
                        doorlockExportVo.setBrandNo(dr.getBrandNo());
                        doorlockExportVos.add(doorlockExportVo);
                    }
                    ExcelWriter excelWriter = EasyExcel.write(fileName, DeviceDoorlockExportVo.class).build();
                    WriteSheet sheet = EasyExcel.writerSheet("sheet1").head(DeviceDoorlockExportVo.class).build();
                    excelWriter.write(doorlockExportVos, sheet);
                    excelWriter.finish();
                } else if (deviceReaVo.getDeviceType().equals("cold_watermeter") || deviceReaVo.getDeviceType().equals("hot_watermeter")) {
                    List<DeviceWorterExportVo> deviceWorterExportVos = new ArrayList<>();
                    for (DeviceReaVo dr : list) {
                        DeviceWorterExportVo deviceWorterExportVo = new DeviceWorterExportVo();
                        deviceWorterExportVo.setDeviceNo(dr.getDeviceThirdNo());
                        deviceWorterExportVo.setRoomName(dr.getRoomName());
                        deviceWorterExportVo.setDeviceType(dr.getDeviceType());
                        deviceWorterExportVo.setUpdateTime(dr.getUpdateTime());
                        if (String.valueOf(dr.getOnlineStatus()).equals("1")) {
                            deviceWorterExportVo.setOnlineStatus("在线");
                        } else {
                            deviceWorterExportVo.setOnlineStatus("离线");
                        }
                        deviceWorterExportVo.setBrandNo(dr.getBrandNo());
                        deviceWorterExportVo.setRemainingAmount(dr.getRemainingAmount());
                        deviceWorterExportVos.add(deviceWorterExportVo);
                    }
                    ExcelWriter excelWriter = EasyExcel.write(fileName, DeviceWorterExportVo.class).build();
                    WriteSheet sheet = EasyExcel.writerSheet("sheet1").head(DeviceWorterExportVo.class).build();
                    excelWriter.write(deviceWorterExportVos, sheet);
                    excelWriter.finish();
                } else if (deviceReaVo.getDeviceType().equals("ammeter")) {
                    List<DeviceAmmterExportVo> deviceAmmterExportVos = new ArrayList<>();
                    for (DeviceReaVo dr : list) {
                        DeviceAmmterExportVo deviceAmmterExportVo = new DeviceAmmterExportVo();
                        deviceAmmterExportVo.setDeviceNo(dr.getDeviceThirdNo());
                        deviceAmmterExportVo.setRoomName(dr.getRoomName());
                        deviceAmmterExportVo.setUpdateTime(dr.getUpdateTime());
                        if (String.valueOf(dr.getOnlineStatus()).equals("1")) {
                            deviceAmmterExportVo.setOnlineStatus("在线");
                        } else {
                            deviceAmmterExportVo.setOnlineStatus("离线");
                        }
                        if (String.valueOf(dr.getPowerStatus()).equals("1")) {
                            deviceAmmterExportVo.setPowerStatus("通电");
                        } else {
                            deviceAmmterExportVo.setPowerStatus("断电");
                        }
                        deviceAmmterExportVo.setBrandNo(dr.getBrandNo());
                        deviceAmmterExportVo.setRemainingAmount(dr.getRemainingAmount());
                        deviceAmmterExportVos.add(deviceAmmterExportVo);
                    }
                    ExcelWriter excelWriter = EasyExcel.write(fileName, DeviceAmmterExportVo.class).build();
                    WriteSheet sheet = EasyExcel.writerSheet("sheet1").head(DeviceAmmterExportVo.class).build();
                    excelWriter.write(deviceAmmterExportVos, sheet);
                    excelWriter.finish();
                }
            }
        }
        String url = oosFileService.oosUploadFile(new File(fileName));
        HousePricingExportResp resp = new HousePricingExportResp();
        resp.setUrl(url);
        resp.setFileName("设备列表.xlsx");
        return CommonResult.success(resp);
    }

    /*
     * @description:新增预警配置
     * @author: James
     * @date: 2023/5/29 16:44
     * @param: [roomSdiotWaring]
     * @return: com.xiaoshuidi.cloud.framework.common.pojo.CommonResult
     **/
    //@PreAuthorize("@ss.hasAnyPermissions('rooms:device:insertWaringConfig')")
    @PostMapping("/device-insertWaringConfig")
    public CommonResult insertWaringConfig(@RequestBody RoomSdiotWaring roomSdiotWaring) {
        return CommonResult.success(iotWaringRepository.save(roomSdiotWaring));
    }

    /*
     * @description:修改预警配置
     * @author: James
     * @date: 2023/5/29 16:48
     * @param: [roomSdiotWaring]
     * @return: com.xiaoshuidi.cloud.framework.common.pojo.CommonResult
     **/
    //@PreAuthorize("@ss.hasAnyPermissions('rooms:device:updateWaringConfig')")
    @PostMapping("/device-updateWaringConfig")
    public CommonResult updateWaringConfig(@RequestBody RoomSdiotWaring roomSdiotWaring) {
        return CommonResult.success(iotWaringRepository.updateById(roomSdiotWaring));
    }

    /*
     * @description:删除预警配置
     * @author: James
     * @date: 2023/5/29 16:50
     * @param: [roomSdiotWaring]
     * @return: com.xiaoshuidi.cloud.framework.common.pojo.CommonResult
     **/
    //@PreAuthorize("@ss.hasAnyPermissions('rooms:device:deleteWaringConfig')")
    @PostMapping("/device-deleteWaringConfig")
    public CommonResult deleteWaringConfig(@RequestParam("roomSdiotWaringId") Long roomSdiotWaringId) {
        return CommonResult.success(iotWaringRepository.removeById(roomSdiotWaringId));
    }

    /*
     * @description:获取预警设置详情 todo @James 返回值要定义泛型, 不要数据库实体直接返回前端
     * @author: James
     * @date: 2023/5/29 17:01
     * @param: [roomSdiotWaringId]
     * @return: com.xiaoshuidi.cloud.framework.common.pojo.CommonResult
     **/
    //@PreAuthorize("@ss.hasAnyPermissions('rooms:device:selecWaringConfigById')")
    @GetMapping("/device-selecWaringConfigById")
    public CommonResult<RoomSdiotWaring> selecWaringConfigById(@RequestParam("id") Long id) {
        return CommonResult.success(iotWaringRepository.getById(id));
    }

    /*
     * @description:查询预警设置列表
     * @author: James
     * @date: 2023/5/29 17:01
     * @param: [roomSdiotWaring]
     * @return: com.xiaoshuidi.cloud.framework.common.pojo.CommonResult
     **/
    //@PreAuthorize("@ss.hasAnyPermissions('rooms:device:selecListWaringConfig')")
    @GetMapping("/device-selecListWaringConfig")
    @Parameters({
            @Parameter(name = "pageSize", description = "页数"),
            @Parameter(name = "pageNum", description = "第几页")
    })
    public CommonResult<IPage<RoomSdiotWaringVo>> selecListtWaringConfig(@RequestParam("pageSize") Integer pageSize, @RequestParam("pageNum") Integer pageNum) {
        IPage<RoomSdiotWaringVo> iPage = new Page(pageNum, pageSize);
        List<RoomSdiotWaringVo> list = iRoomSdiotWaringService.getWaringList();
        for (RoomSdiotWaringVo roomWaringVo : list) {
            List<RoomSdiotAssocationVo> longs = iotRoomAassociationRepository.getWaringInfo(roomWaringVo.getId());
            roomWaringVo.setRoomCount(longs.size());
        }
        int startIndex = (pageNum - 1) * pageSize;
        int endIndex = Math.min(startIndex + pageSize, list.size());
        List<RoomSdiotWaringVo> roomSdiotWaringVoList = list.subList(startIndex, endIndex);
        iPage.setTotal(list.size());
        iPage.setRecords(roomSdiotWaringVoList);
        return CommonResult.success(iPage);
    }

    /*
     * @description:获取预警关联房源的房源id
     * @author: James
     * @date: 2023/5/31 14:20
     * @param: [waringId]
     * @return: com.xiaoshuidi.cloud.framework.common.pojo.CommonResult
     **/
    //@PreAuthorize("@ss.hasAnyPermissions('rooms:device:getWaringInfo')")
    @GetMapping("/device-getWaringInfo")
    public CommonResult getWaringInfo(@RequestParam("waringId") Long waringId) {
        return CommonResult.success(iotRoomAassociationRepository.getWaringInfo(waringId));
    }

    /*
     * @description:预警配置关联房源
     * @author: James
     * @date: 2023/5/29 18:39
     * @param: [roomIds]
     * @return: com.xiaoshuidi.cloud.framework.common.pojo.CommonResult
     **/
    //@PreAuthorize("@ss.hasAnyPermissions('rooms:device:setRoomSdioAassociation')")
    @PostMapping("device-setRoomSdioAassociation")
    @Transactional
    public CommonResult setRoomSdioAassociation(@RequestBody RoomSdioAassociationVo roomSdioAassociationVo) {
        iotRoomAassociationRepository.removeSdiotAssociation(roomSdioAassociationVo.getWaringId());
        List<String> roomIds = roomSdioAassociationVo.getRoomIds();
        if (CollectionUtil.isNotEmpty(roomIds)) {
            List<RoomSdiotAssociation> list = roomIds.stream().map(s -> {
                RoomSdiotAssociation roomSdiotAssociation = new RoomSdiotAssociation();
                roomSdiotAssociation.setRoomId(Long.valueOf(s));
                roomSdiotAssociation.setWaringId(roomSdioAassociationVo.getWaringId());
                roomSdiotAssociation.setDeptId(roomSdioAassociationVo.getDeptId());
                return roomSdiotAssociation;
            }).collect(Collectors.toList());
            iotRoomAassociationRepository.saveBatch(list);
        }
        return CommonResult.success("关联成功");
    }

    /*
     * @description:获取预警信息列表
     * @author: James
     * @date: 2023/6/5 9:49
     * @param: [pageSize, pageNum]
     * @return: com.xiaoshuidi.cloud.framework.common.pojo.CommonResult<com.xiaoshuidi.cloud.framework.common.pojo.PageResult<com.xiaoshuidi.cloud.module.rooms.pojo.RoomSdiotWaringInfo>>
     **/
    //@PreAuthorize("@ss.hasAnyPermissions('rooms:device:waring-info')")
    @GetMapping("/waring-info")
    @Parameters({
            @Parameter(name = "pageSize", description = "页数"),
            @Parameter(name = "pageNum", description = "第几页")
    })
    public CommonResult<IPage<RoomSdiotWaringInfo>> getWaringInfo(@RequestParam("pageSize") Integer pageSize, @RequestParam("pageNum") Integer pageNum) {
        IPage page = iotWaringInfoRepository.page(new <RoomSdiotWaringInfo>Page(pageNum, pageSize));
        return CommonResult.success(page);
    }

    /*
     * @description:获取水电煤设置列表
     * @author: James
     *
     * @date: 2023/6/7 15:05
     * @param: [pageSize, pageNum]
     * @return: com.xiaoshuidi.cloud.framework.common.pojo.CommonResult<com.baomidou.mybatisplus.core.metadata.IPage<com.xiaoshuidi.cloud.module.rooms.pojo.RoomDevicePrice>>
     **/
    //@PreAuthorize("@ss.hasAnyPermissions('rooms:device:selectDevicePriceList')")
    @GetMapping("/device-selectDevicePriceList")
    @Parameters({
            @Parameter(name = "pageSize", description = "页数"),
            @Parameter(name = "pageNum", description = "第几页")
    })
    public CommonResult<IPage<RoomDevicePriceVo>> selectDevicePriceList(@RequestParam("pageSize") Integer pageSize, @RequestParam("pageNum") Integer pageNum) {
        QueryWrapper<RoomDevicePrice> wrapper = new QueryWrapper();
        wrapper.in("type", Arrays.asList(DevicePriceType.DEVICE_PRICE_NORMAL.getCode(), DevicePriceType.DEVICE_PRICE_PEAKVALLEY.getCode()));
        IPage page = iotRoomDevicePriceRepository.page(new <RoomDevicePrice>Page(pageNum, pageSize), wrapper);
        List<RoomDevicePrice> list = page.getRecords();
        List<RoomDevicePriceVo> devicePriceVoList = new ArrayList<>();
        for (RoomDevicePrice roomDevicePrice : list) {
            RoomDevicePriceVo roomDevicePriceVo = new RoomDevicePriceVo();
            List<RoomDiviceAssociationVo> roomIds = iRoomDevicePriceAssociationService.getAssociationList(roomDevicePrice.getId());
//            List<RoomDeviceStairPrice> deviceStairPrices = iRoomDeviceStairPriceService.getRoomDeviceStairPriceList(roomDevicePrice.getId());
//            RoomDeviceStairPrice roomDeviceStairPrice = iRoomDeviceStairPriceService.getRoomDeviceAssociationInfo(roomDevicePrice.getId());
            RoomDevicePeakValleyPrice roomDevicePeakValleyPrice = iRoomDevicePeakValleyPriceService.getRoomDevicePeakValleyPrice(roomDevicePrice.getId());
            RoomDevicePeakValleyPriceVo peakValleyPriceVo = new RoomDevicePeakValleyPriceVo();
            if (roomDevicePeakValleyPrice != null) {
                BeanUtils.copyProperties(roomDevicePeakValleyPrice, peakValleyPriceVo);
            }
            peakValleyPriceVo.setAmmterType(DevicePriceType.getAmmterTypeByCode(roomDevicePrice.getType()));
            roomDevicePriceVo.setId(roomDevicePrice.getId());
            roomDevicePriceVo.setRoomPriceCount(roomIds.size());
            roomDevicePriceVo.setBz(roomDevicePrice.getBz());
            roomDevicePriceVo.setCreateTime(roomDevicePrice.getCreateTime());
            roomDevicePriceVo.setRoomDeviceMapping(roomIds);
            roomDevicePriceVo.setPeakValleyPriceVo(peakValleyPriceVo);
            roomDevicePriceVo.setAmmterPrice(peakValleyPriceVo.getAmmterPrice());
            roomDevicePriceVo.setColdWorterPrice(peakValleyPriceVo.getColdWorterPrice());
            roomDevicePriceVo.setHotWorterPrice(peakValleyPriceVo.getHotWorterPrice());
            roomDevicePriceVo.setPngPrice(peakValleyPriceVo.getPngPrice());
            devicePriceVoList.add(roomDevicePriceVo);
        }
        page.setRecords(devicePriceVoList);
        return CommonResult.success(page);
    }

    /*
     * @description:新增阶梯水电
     * @author: James
     * @date: 2023/6/12 11:28
     * @param: [roomDevicePriceVo]
     * @return: com.xiaoshuidi.cloud.framework.common.pojo.CommonResult
     **/
    //@PreAuthorize("@ss.hasAnyPermissions('rooms:device:insertDevicePrice')")
    @PostMapping("/device-insertDevicePrice")
    @Transactional
    public CommonResult insertDevicePrice(@RequestBody RoomDevicePriceVo roomDevicePriceVo) {
        RoomDevicePrice roomDevicePrice = new RoomDevicePrice();
        roomDevicePrice.setBz(roomDevicePriceVo.getBz());
        roomDevicePrice.setCreateTime(LocalDateTime.now());
        roomDevicePrice.setType(DevicePriceType.getCodeByAmmterType(roomDevicePriceVo.getPeakValleyPriceVo().getAmmterType()));
        iotRoomDevicePriceRepository.save(roomDevicePrice);
        RoomDevicePeakValleyPrice peakValleyPrice = new RoomDevicePeakValleyPrice();
        peakValleyPrice.setRoomDeviceId(roomDevicePrice.getId());
        peakValleyPrice.setAmmterSpikePrice(roomDevicePriceVo.getPeakValleyPriceVo().getAmmterSpikePrice());
        peakValleyPrice.setAmmterPeakPrice(roomDevicePriceVo.getPeakValleyPriceVo().getAmmterPeakPrice());
        peakValleyPrice.setAmmterPlainPrice(roomDevicePriceVo.getPeakValleyPriceVo().getAmmterPlainPrice());
        peakValleyPrice.setAmmterValleyPrice(roomDevicePriceVo.getPeakValleyPriceVo().getAmmterValleyPrice());
        peakValleyPrice.setAmmterPrice(roomDevicePriceVo.getPeakValleyPriceVo().getAmmterPrice());
        peakValleyPrice.setHotWorterPrice(roomDevicePriceVo.getPeakValleyPriceVo().getHotWorterPrice());
        peakValleyPrice.setColdWorterPrice(roomDevicePriceVo.getPeakValleyPriceVo().getColdWorterPrice());
        peakValleyPrice.setPngPrice(roomDevicePriceVo.getPeakValleyPriceVo().getPngPrice());
        iotRoomDevicePeakValleyPriceRepository.save(peakValleyPrice);
        return CommonResult.success("新增成功");
    }

    /*
     * @description:删除阶梯水电配置
     * @author: James
     * @date: 2023/6/12 11:35
     * @param: [deviceStairPriceId]
     * @return: com.xiaoshuidi.cloud.framework.common.pojo.CommonResult
     **/
    //@PreAuthorize("@ss.hasAnyPermissions('rooms:device:deleteDevicePrice')")
//    @PostMapping("/device-deleteDevicePrice")
//    @Transactional
//    public CommonResult deleteDevicePrice(@RequestParam("deviceStairPriceId") Long deviceStairPriceId) {
//        iotRoomDeviceStairPriceRepository.deleteStrirByPriceId(deviceStairPriceId);
//        iotRoomDevicePriceAssociationRepository.removeRoomDevice(deviceStairPriceId);
//        return CommonResult.success(iotRoomDevicePriceRepository.removeById(deviceStairPriceId));
//    }

    /**
     * 删除峰谷水电配置
     * @param devicePeakValleyPriceId
     * @return
     */
    @PostMapping("/device-deleteDevicePrice")
    @Transactional
    public CommonResult deleteDevicePrice(@RequestParam("devicePeakValleyPriceId") Long devicePeakValleyPriceId) {
        iotRoomDevicePeakValleyPriceRepository.deleteByPriceId(devicePeakValleyPriceId);
        iotRoomDevicePriceAssociationRepository.removeRoomDevice(devicePeakValleyPriceId);
        return CommonResult.success(iotRoomDevicePriceRepository.removeById(devicePeakValleyPriceId));
    }

    /*
     * @description:修改阶梯水电配置
     * @author: James
     * @date: 2023/6/12 11:50
     * @param: [roomDevicePriceVo]
     * @return: com.xiaoshuidi.cloud.framework.common.pojo.CommonResult
     **/
    //@PreAuthorize("@ss.hasAnyPermissions('rooms:device:updateDevicePrice')")
    @PostMapping("/device-updateDevicePrice")
    @Transactional
    public CommonResult updateDevicePrice(@RequestBody RoomDevicePriceVo roomDevicePriceVo) {

        if (roomDevicePriceVo.getId() == null) {
            return CommonResult.error(GlobalErrorCodeConstants.BAD_REQUEST);
        }
        RoomDevicePrice roomDevicePrice = new RoomDevicePrice();
        roomDevicePrice.setBz(roomDevicePriceVo.getBz());
        roomDevicePrice.setId(roomDevicePriceVo.getId());
        roomDevicePrice.setType(DevicePriceType.getCodeByAmmterType(roomDevicePriceVo.getPeakValleyPriceVo().getAmmterType()));
        iotRoomDevicePriceRepository.updateById(roomDevicePrice);
        //先删除原有配置再添加
        iotRoomDevicePeakValleyPriceRepository.deleteByPriceId(roomDevicePriceVo.getId());
        RoomDevicePeakValleyPrice peakValleyPrice = new RoomDevicePeakValleyPrice();
        peakValleyPrice.setRoomDeviceId(roomDevicePrice.getId());
        peakValleyPrice.setAmmterSpikePrice(roomDevicePriceVo.getPeakValleyPriceVo().getAmmterSpikePrice());
        peakValleyPrice.setAmmterPeakPrice(roomDevicePriceVo.getPeakValleyPriceVo().getAmmterPeakPrice());
        peakValleyPrice.setAmmterPlainPrice(roomDevicePriceVo.getPeakValleyPriceVo().getAmmterPlainPrice());
        peakValleyPrice.setAmmterValleyPrice(roomDevicePriceVo.getPeakValleyPriceVo().getAmmterValleyPrice());
        peakValleyPrice.setAmmterPrice(roomDevicePriceVo.getPeakValleyPriceVo().getAmmterPrice());
        peakValleyPrice.setHotWorterPrice(roomDevicePriceVo.getPeakValleyPriceVo().getHotWorterPrice());
        peakValleyPrice.setColdWorterPrice(roomDevicePriceVo.getPeakValleyPriceVo().getColdWorterPrice());
        peakValleyPrice.setPngPrice(roomDevicePriceVo.getPeakValleyPriceVo().getPngPrice());
        iotRoomDevicePeakValleyPriceRepository.save(peakValleyPrice);
        return CommonResult.success("修改成功");
    }

    /*
     * @description:阶梯水电关联房源
     * @author: James
     * @date: 2023/6/12 13:53
     * @param: [roomDevicePriceVo]
     * @return: com.xiaoshuidi.cloud.framework.common.pojo.CommonResult
     **/
    //@PreAuthorize("@ss.hasAnyPermissions('rooms:device:setDevicePriceRoom')")
    @PostMapping("device-setDevicePriceRoom")
    @Transactional
    public CommonResult setDevicePriceRoom(@RequestBody RoomDevicePriceVo roomDevicePriceVo) {
        iotRoomDevicePriceAssociationRepository.deleteRoomDevice(roomDevicePriceVo.getId(), roomDevicePriceVo.getApartmentId());
        List<Long> roomIds = roomDevicePriceVo.getRoomPriceIds();
        if (CollectionUtil.isNotEmpty(roomIds)) {
            List<RoomDevicePriceAssociation> list = roomIds.stream().map(s -> {
                RoomDevicePriceAssociation roomSdiotAssociation = new RoomDevicePriceAssociation();
                roomSdiotAssociation.setRoomId(s);
                roomSdiotAssociation.setDevicePriceId(roomDevicePriceVo.getId());
                roomSdiotAssociation.setDeptId(roomDevicePriceVo.getDeptId());
                return roomSdiotAssociation;
            }).collect(Collectors.toList());
            iotRoomDevicePriceAssociationRepository.saveBatch(list);
        }
        return CommonResult.success("关联成功");
    }

    /*
     * @description:过滤房源
     * @author: James
     * @date: 2023/6/13 15:46
     * @param: [priceId]
     * @return: com.xiaoshuidi.cloud.framework.common.pojo.CommonResult
     **/
    @GetMapping("/device-getNotInRoom")
    public CommonResult getNotInRoom(@RequestParam("priceId") Long priceId) {
        List<Long> roomId = new ArrayList<>();
        List<RoomDevicePriceAssociation> notInRoom = iotRoomDevicePriceAssociationRepository.getNotInRoom(priceId, DevicePriceType.DEVICE_PRICE_STEP.getCode());
        if (CollectionUtil.isNotEmpty(notInRoom)) {
            roomId = notInRoom.stream().map(s -> s.getRoomId()).collect(Collectors.toList());
        }
        return CommonResult.success(roomId);
    }

    /*
     * @description:手抄表过滤房源
     * @author: James
     * @date: 2023/7/8 16:50
     * @param: [priceId]
     * @return: com.xiaoshuidi.cloud.framework.common.pojo.CommonResult
     **/
    @GetMapping("/device-getLaterRoom")
    public CommonResult getLaterRoom(@RequestParam("priceId") Long priceId) {
        List<Long> roomId = new ArrayList<>();
        List<RoomDevicePriceAssociation> notInRoom = iotRoomDevicePriceAssociationRepository.getNotInRoom(priceId, DevicePriceType.DEVICE_PRICE_UNSTEP.getCode());
        if (CollectionUtil.isNotEmpty(notInRoom)) {
            roomId = notInRoom.stream().map(s -> s.getRoomId()).collect(Collectors.toList());
        }
        return CommonResult.success(roomId);
    }


    /*
     * @description:过滤房源
     * @author: James
     * @date: 2023/6/13 15:46
     * @param: [priceId]
     * @return: com.xiaoshuidi.cloud.framework.common.pojo.CommonResult
     **/
    @GetMapping("/device-getNotRoomIdPay")
    public CommonResult getNotRoomIdPay() {
        return CommonResult.success(iotRoomDevicePriceAssociationRepository.getNotRoomIdPay());
    }

    /*
     * @description:根据房源id查询房间设备 todo @James 返回值要定义泛型
     * @author: James
     * @date: 2023/6/15 20:17
     * @param: [roomId]
     * @return: com.xiaoshuidi.cloud.framework.common.pojo.CommonResult
     **/
    @GetMapping("/device-getDeviceTypeList")
    public CommonResult getDeviceTypeList(@RequestParam("roomId") Long roomId) {
        return CommonResult.success(roomSdiotDeviceMappingService.getDeviceListByRoomId(roomId));
    }

    /*
     * @description:智能设备退租清算 todo @James 常量要定义响应的枚举或常量类
     * @author: James
     * @date: 2023/6/29 18:31
     * @param: [roomHouseId]
     * @return: com.xiaoshuidi.cloud.framework.common.pojo.CommonResult<com.xiaoshuidi.cloud.module.rooms.vo.DevicePayTypeVo>
     **/
    @GetMapping("/getDevicePriceByRoomId")
    public CommonResult<DevicePayTypeVo> getDevicePriceByRoomId(@RequestParam("roomHouseId") Long roomHouseId, @RequestParam("charging") Boolean charging) {
        CommonResult<DevicePayTypeVo> devicePriceVoResultModel = new CommonResult<>();
        DevicePayTypeVo devicePayTypeVo = new DevicePayTypeVo();
        //刷新水电表
        List<DeviceReaVo> dviceIds = iotDeviceRepository.getDviceIds(roomHouseId);
        log.info("根据房间id获取设备信息：" + JSONObject.toJSONString(dviceIds));
        if (dviceIds.size() > 0) {
            for (DeviceReaVo deviceId : dviceIds) {
                if (deviceId.getDeviceType().equals("hot_watermeter") || deviceId.getDeviceType().equals("cold_watermeter")) {
                    deviceApi.refreshWatermeterInfo1(deviceId.getDeviceNo(), roomHouseId, charging);
                } else {
                    deviceApi.refreshAmmeterInfo1(deviceId.getDeviceNo(), roomHouseId, charging);
                }
            }
        }
        //预付费
        List<RoomDeviceStairVo> beforeDevice = iotDeviceService.getBeforeDevice(roomHouseId);
        log.info("预付费信息：" + JSONObject.toJSONString(beforeDevice));
        //过滤后付费项
        List<String> feeType = new ArrayList<>();
        for (RoomDeviceStairVo stairVo : beforeDevice) {
            if (stairVo.getDeviceType().equals("电表")) {
                feeType.add("电费");
            } else if (stairVo.getDeviceType().equals("热水表")) {
                feeType.add("热水费");
            } else if (stairVo.getDeviceType().equals("冷水表")) {
                feeType.add("冷水费");
            }
        }
        List<RoomDeviceStairVo> laterDevice = iotDeviceService.getlaterDevice(roomHouseId, feeType);
        log.info("后付费信息：" + JSONObject.toJSONString(laterDevice));
        devicePayTypeVo.setBdforePayType(beforeDevice);
        devicePayTypeVo.setLaterPayType(laterDevice);
        devicePriceVoResultModel.setData(devicePayTypeVo);
        return devicePriceVoResultModel;
    }

    /*
     * @description:批量退租清算 todo @James 常量要定义响应的枚举或常量类
     * @author: James
     * @date: 2023/6/29 18:31
     * @param: [roomHouseId]
     * @return: com.xiaoshuidi.cloud.framework.common.pojo.CommonResult<com.xiaoshuidi.cloud.module.rooms.vo.DevicePayTypeVo>
     **/
    @PostMapping("/getDevicePriceByRoomIds")
    public CommonResult<List<DevicePayTypeVo>> getDevicePriceByRoomIds(@RequestBody List<RoomIdsVo> roomHouseIds) {
        CommonResult<List<DevicePayTypeVo>> devicePriceVoResultModel = new CommonResult<>();
        List<DevicePayTypeVo> devicePayTypeVos = new ArrayList<>();
        for (RoomIdsVo roomId : roomHouseIds) {
            Long roomHouseId = roomId.getRoomId();
            DevicePayTypeVo devicePayTypeVo = new DevicePayTypeVo();
            //刷新水电表
            List<DeviceReaVo> dviceIds = iotDeviceRepository.getDviceIds(roomHouseId);
            if (dviceIds.size() > 0) {
                for (DeviceReaVo deviceId : dviceIds) {
                    if (deviceId.getDeviceType().equals("hot_watermeter") || deviceId.getDeviceType().equals("cold_watermeter")) {
                        deviceApi.refreshWatermeterInfo1(deviceId.getDeviceNo(), roomHouseId, roomId.getCharging());
                    } else {
                        deviceApi.refreshAmmeterInfo1(deviceId.getDeviceNo(), roomHouseId, roomId.getCharging());
                    }
                }
            }
            //预付费
            List<RoomDeviceStairVo> beforeDevice = iotDeviceService.getBeforeDevice(roomHouseId);
            //过滤后付费项
            List<String> feeType = new ArrayList<>();
            for (RoomDeviceStairVo stairVo : beforeDevice) {
                if (stairVo.getDeviceType().equals("电表")) {
                    feeType.add("电费");
                } else if (stairVo.getDeviceType().equals("热水表")) {
                    feeType.add("热水费");
                } else if (stairVo.getDeviceType().equals("冷水表")) {
                    feeType.add("冷水费");
                }
            }
            List<RoomDeviceStairVo> laterDevice = iotDeviceService.getlaterDevice(roomHouseId, feeType);
            devicePayTypeVo.setBdforePayType(beforeDevice);
            devicePayTypeVo.setLaterPayType(laterDevice);
            devicePayTypeVo.setRoomHouseId(roomHouseId);
            devicePayTypeVos.add(devicePayTypeVo);
        }
        devicePriceVoResultModel.setData(devicePayTypeVos);
        return devicePriceVoResultModel;
    }

    /*
     * @description:退租清算 todo @James 常量要定义响应的枚举或常量类
     * @author: James
     * @date: 2023/6/29 18:33
     * @param: [roomHouseId]
     * @return: com.xiaoshuidi.cloud.framework.common.pojo.CommonResult<com.xiaoshuidi.cloud.module.rooms.vo.DevicePayTypeVo>
     **/
    @PostMapping("/updateSage")
    public CommonResult updateSage(@RequestBody List<RoomDeviceStairVo> roomDeviceStairVos) {
        //根据房源id获取已关联的设备
        for (RoomDeviceStairVo stairVo : roomDeviceStairVos) {
            DeviceDosageVo deviceDosageVo = new DeviceDosageVo();
            deviceDosageVo.setDeviceNo(stairVo.getDeviceNo());
            deviceDosageVo.setEndAmount(stairVo.getEndRead());
            deviceDosageVo.setStartAmount(stairVo.getStartRead());
            deviceDosageVo.setDeviceThirdNo(stairVo.getDeviceThirdNo());
            deviceDosageVo.setRoomId(stairVo.getRoomHouseId());
            deviceDosageVo.setPayType(stairVo.getPayType());
            deviceDosageVo.setPrice(stairVo.getPrice());
            if (stairVo.getDeviceType().equals("热水表")) {
                deviceDosageVo.setDeviceType("hot_watermeter");
            } else if (stairVo.getDeviceType().equals("冷水表")) {
                deviceDosageVo.setDeviceType("cold_watermeter");
            }
            deviceApi.updateSage(deviceDosageVo);
        }
        return CommonResult.success("清算成功！");
    }
}